package org.bb.basic_java_api.common.util;

import lombok.SneakyThrows;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.sniff.ElasticsearchNodesSniffer;
import org.elasticsearch.client.sniff.NodesSniffer;
import org.elasticsearch.client.sniff.Sniffer;

public class HighLevelClient {
    private static RestClientBuilder restClientBuilder = ClientBuilders.getClientBuilder();

    // 实例化客户端
    private static RestHighLevelClient restHighLevelClient;
    // 嗅探器初始化
    private static Sniffer sniffer;

    public RestHighLevelClient getClient() {
        restHighLevelClient = new RestHighLevelClient(restClientBuilder);
        // 五秒钟刷新并更新一次节点
        sniffer = Sniffer.builder(restHighLevelClient.getLowLevelClient()).setSniffAfterFailureDelayMillis(5000).build();


        // 2.使用https
        /*NodesSniffer nodesSniffer = new ElasticsearchNodesSniffer(
                sniffer,
                ElasticsearchNodesSniffer.DEFAULT_SNIFF_REQUEST_TIMEOUT,
                ElasticsearchNodesSniffer.Scheme.HTTPS
        );*/

        return restHighLevelClient;
    }

    @SneakyThrows
    public void closeClient() {
        if (null != restHighLevelClient) {
            restHighLevelClient.close();
        }
    }
}
